package com.wish.g04.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.g04.base.entity.User;
import com.wish.g04.base.entity.UserRole;
import com.wish.g04.base.service.IUserRoleService;
import com.wish.g04.base.service.IUserService;
import com.wish.g04.business.dto.UserDTO;
import com.wish.g04.business.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class TbUserServiceImpl implements UserService {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Override
    public void updateUser(UserDTO userDTO) {

        if (StringUtils.isBlank(userDTO.getPassword())) {
            userDTO.setPassword(null);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        iUserService.updateById(user);

        //先删除用户与角色的关系表
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userDTO.getUserId());
        iUserRoleService.remove(queryWrapper);
        //然后在添加
        ArrayList<UserRole> arrayList = new ArrayList<>();
        userDTO.getRoleIdList().forEach(role->{
            UserRole userRole = new UserRole();
            userRole.setUserId(userDTO.getUserId()).setRoleId(role);
            arrayList.add(userRole);
        });
        iUserRoleService.saveBatch(arrayList);


    }
}
